﻿using UnityEngine;
using System.Collections;
using System;

public class AnimateObjects : MonoBehaviour 
{
    public GameObject[] animationObjects;
    public AnimationClip[] customAnimations;

    protected Animation[] animComponents;
    protected string[] clipNames;

    protected virtual void Awake()
    {
        if (animationObjects.Length == customAnimations.Length)
        {
            animComponents = new Animation[animationObjects.Length];
            clipNames = new string[animationObjects.Length];
        }
        else
        {
            throw new NullReferenceException("AnimationObjects.Length != CustomAnimations.Length");
        }
    }

    protected virtual void Start()
    {
        for (int index = 0; index < animationObjects.Length; index++)
        {
            if (customAnimations[index] == null)
            {
                throw new ArgumentNullException("CustomAnimation[" + index + "] is null");
            }

            clipNames[index] = Convert.ToString(UnityEngine.Random.Range(long.MinValue, long.MaxValue));
            clipNames[index] += Time.time;
            clipNames[index] += animationObjects[index].name;

            animComponents[index] = animationObjects[index].GetComponent<Animation>();
            if (animComponents[index] == null)
                animComponents[index] = animationObjects[index].AddComponent<Animation>();

            animationObjects[index].SetActive(true);

            animComponents[index].AddClip(customAnimations[index], clipNames[index]);
        }
    }

    public void Animate()
    {
        for (int index = 0; index < animationObjects.Length; index++)
        {
            animComponents[index].CrossFade(clipNames[index]);
        }
    }
}
